package com.ds.smartstudio.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.ds.smartstudio.controller.WebSocket;
import com.ds.smartstudio.entity.History;
import com.ds.smartstudio.handler.MqttMessageHandler;
import com.ds.smartstudio.service.BO.DeviceMqttMessage;
import com.ds.smartstudio.service.DeviceService;
import com.ds.smartstudio.service.HistoryService;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;
import java.util.List;


@Slf4j
@Configuration
public class MyMQTTCallback implements MqttCallback {

    private MyMQTTClient myMQTTClient;


    public MyMQTTCallback(MyMQTTClient myMQTTClient) {
        this.myMQTTClient = myMQTTClient;
    }

    /**
     * 丢失连接，可在这里做重连
     * 只会调用一次
     *
     * @param throwable
     */
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt connectionLost 连接断开，5S之后尝试重连: {}", throwable.getMessage());
        long reconnectTimes = 1;
        while (true) {
            try {
                if (MyMQTTClient.getClient().isConnected()) {
                    log.warn("mqtt reconnect success end");
                    return;
                }
                log.warn("mqtt reconnect times = {} try again...", reconnectTimes++);
                MyMQTTClient.getClient().reconnect();
            } catch (MqttException e) {
                log.error(e.toString());
            }
            try {
                Thread.sleep(5000);
            } catch (InterruptedException ignored) {
            }
        }
    }

    /**
     * @param topic
     * @param mqttMessage
     * @throws Exception
     * subscribe后得到的消息会执行到这里面
     */
    @Override
    public void messageArrived(String topic, MqttMessage mqttMessage) {


        try {
            String msg = new String(mqttMessage.getPayload());
            log.info("接收消息主题 : {}，接收消息内容 : {}", topic, msg);
            MqttMessageHandler.receive(topic, msg);


        } catch (Exception e) {
            log.error(e.toString());
        }
    }

    /**
     * 消息到达后
     * subscribe后，执行的回调函数
     *
     * @param s
     * @param mqttMessage
     * @throws Exception
     */
    /**
     * publish后，配送完成后回调的方法
     *
     * @param iMqttDeliveryToken
     */
    @Override
    public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
        log.info("==========deliveryComplete={}==========", iMqttDeliveryToken.isComplete());
    }
    @Component
    public static class SaveData {
        @Autowired
        private WebSocket webSocket;

        private static SaveData saveData;
        @PostConstruct
        public void init() {
            saveData = this;
            saveData.webSocket = webSocket;
        }
    }
}
